//公共方法
var Vue = require('vue');

function get(url, param = '', callBack, failBack = null) {
    let sessionId = getCookie('sessionId');
    url = `${param}` ? `${url}${param}` : url;
    // for(let item in query){
    //     url = `${url}?${item}=${query[item]}`;
    // }
    Vue.default.http.get(url, { headers: { 'sessionId': sessionId }, emulateJSON: true }).then(res => {
        callBack(res.body)
    }, res => {
        if (failBack) {
            failBack(res.body)
        }
    });
}

function getToDayDate(count) {
    var date1 = new Date();
    if (count) {
        var date1 = new Date(Date.parse(date1) + 86400000 * 2);
    }
    console.log('date1')
    console.log(date1)
    var ys = date1.getFullYear()
    var ms = date1.getMonth() + 1
    var ds = date1.getDate()
    var toDay = ys +
        "-" +
        (ms < 10 ? "0" + ms : ms) +
        "-" +
        (ds < 10 ? "0" + ds : ds)
    console.log('toDay');
    console.log(toDay);
    return toDay
}

function deleteRequest(url, param = '', callBack, failBack = null) {
    let sessionId = getCookie('sessionId');
    url = `${param}` ? `${url}${param}` : url;
    Vue.default.http.delete(url, { headers: { 'sessionId': sessionId }, emulateJSON: true }).then(res => {
        callBack(res.data)
    }, res => {
        if (failBack) {
            failBack(res.data)
        }
    });
}


function post(url, param, callBack, failBack = null) {
    let sessionId = getCookie('sessionId');
    if (url.substr(url.length - 1, 1) == '/') {
        url = `${param}` ? `${url}${param}` : url;
        param = ''
    } else {
        for (let item in param) {
            if (!param[item] && param[item] !== false) {
                delete param[item]
            }
        }
    }

    Vue.default.http.post(url, JSON.stringify(param), { headers: { 'sessionId': sessionId }, emulateJSON: true }).then(res => {
        callBack(res.body)
    }, res => {
        if (failBack) {
            failBack(res.body)
        }
    });
}

function put(url, param, contentType, callBack, failBack = null) {
    let sessionId = getCookie('sessionId');
    // if (url.substr(url.length-1,1) == '/') {
    //   url = `${param}`?`${url}${param}`:url;
    //   param = ''
    // } else {
    //   for (let item in param) {
    //     if (!param[item] && param[item] !== false) {
    //       delete param[item]
    //     }
    //   }
    // }

    Vue.default.http.put(url, param, { headers: { 'Content-Type': contentType }, emulateJSON: false }).then(res => {
        callBack(res.body)
    }, res => {
        if (failBack) {
            failBack(res.body)
        }
    });
}

// function uploadFile(url,param,contentType,suffix,callBack,failBack=null) {   // 上传图片到阿里云 / 腾讯云
// 	Vue.default.http.post(url, param, {headers:{'Content-Type':contentType,'suffix':suffix},emulateJSON: false}).then(res => {
// 		callBack(res.data)
// }, res => {
// 		if(failBack){
// 			failBack(res.data)
// 		}
// 	});
// }
function uploadFile(url, param, contentType, callBack, failBack = null) { // 上传图片到阿里云 / 腾讯云
    console.log(contentType);
    Vue.default.http.put(url, param, { headers: { 'Content-Type': contentType }, emulateJSON: false }).then(res => {
        console.log(res);
        callBack(res.data)
    }, res => {
        if (failBack) {
            failBack(res.data)
        }
    });
}

function requestAjax(url, param, dataForm = null, callBack, failBack = null) {
    // let sessionId = sessionStorage.getItem('sessionId');
    // let sendUrl = url + '?sessionId=' + sessionId;
    let sendUrl = url
    let params;
    // if(typeof(param))
    if (typeof(param) == 'string') {
        params = JSON.parse(param)
        for (let item in params) {
            if (!params[item] && params[item] !== false) {
                delete params[item]
            }
        }
        params = JSON.stringify(params)
    } else {
        params = param
    }



    for (let item in dataForm) {
        sendUrl = sendUrl + "&" + item + '=' + dataForm[item];
    }
    Vue.default.http.post(sendUrl, params, { emulateJSON: true, credentials: true }).then(res => {
        callBack(res.data)
    }, res => {
        if (failBack) {
            failBack(res.data)
        }
    });
}

function dateFormate(num, type = 'date') {
    var d = new Date(num);
    var year = d.getFullYear();
    var day = d.getDate();
    var month = +d.getMonth() + 1;
    var hour = d.getHours();
    var minute = d.getMinutes();
    var second = d.getSeconds();
    if (type == 'date') {
        var f = year + "-" + formate(month) + "-" + formate(day) + " " + formate(hour) + ":" + formate(minute) + ":" + formate(second);
    } else if (type == 'birth') {
        var f = year + "-" + formate(month) + "-" + formate(day)
    }

    function formate(d) {
        return d > 9 ? d : '0' + d;
    }
    return f;
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); // 匹配目标参数
    var result = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
    if (result != null) {
        return decodeURIComponent(result[2]);
    } else {
        return null;
    }
}

function timeStampToDate(timestamp) {
    var enMonthList = ["Jan", 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
    var date = new Date(timestamp * 1000),
        y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

    return enMonthList[m] + " " + d + ", " + y
}

//设置cookie1：
function setCookie(name, value, time) {
    let Days = 365;
    exp = new Date();
    if (time) {
        exp.setTime(exp.getTime() + time * 60 * 1000);
    } else {
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    }
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

//读取cookie：
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null;
}

//判断ios
function isIOS() {
    let isIphone = navigator.userAgent.includes('iPhone')
    let isIpad = navigator.userAgent.includes('iPad')
    return isIphone || isIpad
}

function inputBlur() {
    setTimeout(function() {
        var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
        window.scrollTo(0, Math.max(scrollHeight - 1, 0));
    }, 300);
}

/**
 * 设置微信网页标题
 * @param {number | string } title 你要设置的标题
 */
function setPageTitle(title) {
    document.title = title
    var mobile = navigator.userAgent.toLowerCase()
    if (/iphone|ipad|ipod/.test(mobile)) {
        var iframe = document.createElement('iframe')
        iframe.style.display = 'none'
            // 替换成站标favicon路径或者任意存在的较小的图片即可
            // iframe.setAttribute('src', '/favicon.ico')
        var iframeCallback = function() {
            setTimeout(function() {
                iframe.removeEventListener('load', iframeCallback)
                document.body.removeChild(iframe)
            }, 0)
        }
        iframe.addEventListener('load', iframeCallback)
        document.body.appendChild(iframe)
    }
}

function isOnloadPage() {
    if (typeof window.WeixinJSBridge == "undefined") {
        console.log(246)
        sessionStorage.setItem('isload','1')
        location.reload()
    }
}
module.exports = {
    post,
    put,
    get,
    dateFormate,
    timeStampToDate,
    setCookie,
    getCookie,
    setPageTitle,
    isIOS,
    deleteRequest,
    uploadFile,
    getToDayDate,
    isOnloadPage,
    getQueryString,
    inputBlur
}